import Foundation
import EventKit

/// 日历事件管理器，用于获取和管理系统日历事件
@available(macOS 14.0, *)
class CalendarEventManager: ObservableObject {
    private let eventStore = EKEventStore()
    @Published var events: [EKEvent] = []
    @Published var authorizationStatus: EKAuthorizationStatus = .notDetermined
    
    /// 请求日历访问权限
    @available(macOS 14.0, *)
    func requestAccess() {
        if #available(macOS 14.0, *) {
            eventStore.requestFullAccessToEvents { [weak self] (granted, error) in
                DispatchQueue.main.async {
                    self?.authorizationStatus = EKEventStore.authorizationStatus(for: .event)
                    if granted {
                        self?.fetchEvents()
                    } else if let error = error {
                        print("日历访问权限被拒绝: \(error)")
                    }
                }
            }
        }
    }
    
    /// 获取指定日期的事件
    @available(macOS 14.0, *)
    func fetchEvents(for date: Date = Date()) -> [EKEvent] {
        guard authorizationStatus == .authorized else {
            return []
        }
        
        let calendar = Calendar.current
        let startOfDay = calendar.startOfDay(for: date)
        guard let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay) else {
            return []
        }
        
        let predicate = eventStore.predicateForEvents(withStart: startOfDay, end: endOfDay, calendars: nil)
        let events = eventStore.events(matching: predicate)
        
        return events.sorted { (event1, event2) -> Bool in
            guard let startDate1 = event1.startDate, let startDate2 = event2.startDate else {
                return false
            }
            return startDate1 < startDate2
        }
    }
    
    /// 获取指定日期范围的事件
    @available(macOS 14.0, *)
    func fetchEvents(from startDate: Date, to endDate: Date) -> [EKEvent] {
        guard authorizationStatus == .authorized else {
            return []
        }
        
        let predicate = eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: nil)
        let events = eventStore.events(matching: predicate)
        
        return events.sorted { (event1, event2) -> Bool in
            guard let startDate1 = event1.startDate, let startDate2 = event2.startDate else {
                return false
            }
            return startDate1 < startDate2
        }
    }
    
    /// 获取当前日期的事件并更新发布者
    @available(macOS 14.0, *)
    func fetchEvents() {
        let todayEvents: [EKEvent] = fetchEvents()
        DispatchQueue.main.async {
            self.events = todayEvents
        }
    }
    
    /// 检查权限状态
    @available(macOS 14.0, *)
    func checkAuthorizationStatus() {
        authorizationStatus = EKEventStore.authorizationStatus(for: .event)
        if authorizationStatus == .authorized {
            fetchEvents()
        }
    }
}